<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/27
 * 描述:
 */

namespace app\result\admin;

use app\model\AccessLog;
use app\model\order\Order;
use app\model\SysStatistics;
use app\model\user\User;
use app\result\BaseResult;

class SysStatisticsResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new SysStatistics();
    }

    public static function create(): array
    {
        $ckey = 'sys_statistics_data' . date('Ymd');
        if (cache($ckey)) {
            // return self::success_return('已经进行统计');
        }
        cache($ckey, 1, 3600);
        $model = new SysStatistics();

        $date = date('Y-m-d', strtotime("-1 day"));//昨天

        if ($model->where('date', $date)->value('id')) {
            //return self::success_return('已经进行统计');
        }
        $dateStart = $date . ' 00:00:00';
        $dateEnd = $date . ' 23:59:59';
        $year = date('Y', strtotime($date));
        $month = date('m', strtotime($date));
        $day = date('d', strtotime($date));
        $modelUser = new User();
        $modelOrder = new Order();
        $whereOrder = [];
        $whereOrder[] = ['order_status', 'in', '0,1,2,4,5,7'];//0=待支付，1=待发货，2=待收货，3=待评价，4=已完成，5=售后中，6=已取消，7=待审核
        $whereOrder[] = ['created_at', 'between', [$dateStart, $dateEnd]];
        $reg_user_count = $modelUser->data_count([['created_at', 'between', [$dateStart, $dateEnd]]]);
        $active_user_count = $modelUser->data_count([['last_active_time', 'between', [$dateStart, $dateEnd]]]);
        $order_count = $modelOrder->data_count($whereOrder);
        $amount_total = $modelOrder->data_sum($whereOrder, 'order_pay_price');//应付金额
        $order_amount_paid = $modelOrder->data_sum($whereOrder, 'pay_price');
        $order_user_count = $modelOrder->data_count($whereOrder, 'user_id', 'user_id');
        $api_count = (new AccessLog())->data_count([['created_at', 'between', [$dateStart, $dateEnd]]]);
        $baseData = [
            'date' => $date,
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'reg_user_count' => $reg_user_count,
            'active_user_count' => $active_user_count,
            'order_count' => $order_count,
            'order_amount' => $amount_total,
            'order_amount_paid' => $order_amount_paid,
            'order_user_count' => $order_user_count,
            'api_count' => $api_count,
        ];
        bs_log($baseData, 'SysStatistics', 'sys_statistics.log');

        //兼容手动二次执行
        if ($id = $model->where('date', $date)->value('id')) {
            $model->where('id', $id)->update($baseData);
        } else {
            $res = $model->save($baseData);
            if (!$res) {
                cache($ckey, null);
                return self::error_return('保存失败');
            }
        }

        return self::success_return('success', $baseData);
    }

    public function list($args)
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $date_range = $args['date_range'] ?? [];
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['date', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if ($date_range) {
            $where[] = ['date', 'between', $date_range];
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'id desc', $page, $pageSize);
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }
}
